import { useReducer, createContext, useContext } from 'react'
const MyContext = createContext()
const init = (initialCount) => {
  return {
    count: initialCount | 10
  }
}
const reducer = (state, action) => {
  switch (action.type) {
    case 'increment':
      return {...state, count: state.count + 1}
    case 'decrement':
      return {...state, count: state.count - 1}
    case 'reset':
      return init(action.payload)
    default:
      return new Error()
  }
}

const Child = ({ initialCount }) => {
  // console.log(initialCount)
  const count = useContext(MyContext)
  const [ state, dispatch ] = useReducer(reducer, count, init)
  console.log(state)
  return (
    <div>
      { count }
      <button onClick = {() => dispatch({ type : 'decrement' })} >-</button>
        { state.count }
      <button onClick = {() => dispatch({ type : 'increment' })} >+</button>
    </div>
  )
}
const App = ({ initialCount }) => {
  // console.log('initialCount', initialCount)
  const [ state, dispatch ] = useReducer(reducer, initialCount, init)
  // console.log(state)
  return (
    <>
      <button onClick = {() => dispatch({ type : 'decrement' })} >-</button>
        { state.count }
      <button onClick = {() => dispatch({ type : 'increment' })} >+</button>
      <button onClick = {() => dispatch({ type : 'reset', payload: initialCount})} >重置</button>
      <hr></hr>
      <MyContext.Provider value={ state.count }>
        <Child/>
      </MyContext.Provider>
      
    </>
  )
}

export default App